<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    #box{
        margin:150px auto;
        border: red 1px solid;
        width: 350px;
    }

    #button{
        width: 200px;
        height: 54px;
        font-size: 35px;
    }

    #show{
        font-size: 35px;
    }
</style>
<body onload="suningAPI(),getDateTime()">
<div id="box" >
    <input id="button" type="button" value="生成验证码" onclick="suningAPI(),getDateTime()">
    <span id="show" style="padding-left: 10px">生成中...</span>
</div>

</body>

<script>
    //当前的网络时间
    let dateTime = null;
    let dateTimeStr = null; //2023-05-17 20:47:07

    //----------------------------
    //用于从网络获取当前时间，该开放的API由苏宁提供，服务不是很稳定，所以调用时可能需要多次调用
    function suningAPI(){
        dateTime = null;
        dateTimeStr = null;
        let show = document.getElementById("show");
        show.innerText = "生成中...";

        let httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', 'https://quan.suning.com/getSysTime.do', true);
        httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        httpRequest.send(null);
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                dateTime = httpRequest.responseText;
            }
        };
    }

    //----------------------------
    //count : 轮询4次(2秒)查看dateTime是否有值，如果无值，就再次调用suningAPI()向服务器发请求
    //myTime: 定时器，请求到时间后需要清除定时器
    let count = 0;
    let myTimer = null;
    function getDateTime() {
        myTimer = window.setTimeout(getDateTime, 500);//调用自己
        count++;
        if(count>=4){
            suningAPI();
            count = 0;
        }
        if (dateTime != null) {
            dateTimeStr = dateTime.toString().split('"')[3];
            //alert(dateTimeStr)
            window.clearTimeout(myTimer);
            show();
        }
    }

    //---------------------------- dateTimeStr
    //2023-05-17 20:47:07
    function show(){
        let args01 = dateTimeStr.split(" ")[0].split("-")[0];//年
        let args02 = dateTimeStr.split(" ")[0].split("-")[1];//月
        let args03 = dateTimeStr.split(" ")[0].split("-")[2];//日
        let args04 = dateTimeStr.split(" ")[1].split(":")[0];//时
        let args05 = dateTimeStr.split(" ")[1].split(":")[1];//分

        //alert(args01 + "," + args02 + "," + args03 + "," + args04 + "," + args05);

        let sum = args01 * (args02 + args03 + args04 + Math.floor(args05/3));
        let show = document.getElementById("show");
        show.innerText = (1000+sum%9000);
    }





</script>

</html>